import React, { Component } from "react";

export default class App extends Component {
  state = {
    inputVal: "🐸🐸🐸🐸🐸",
    todos: [],
  };
  handleChange = (e) => {
    console.log(e.target.value);
    this.setState({
      inputVal: e.target.value,
    });
  };
  handleAddTodos = (params) => {
    // 新建一个todos
    let newTodo = {
      id: Date.now(),
      text: this.state.inputVal,
    };
    // 深拷贝旧的todos
    let newTodos = JSON.parse(JSON.stringify(this.state.todos));
    newTodos.push(newTodo);
    // 更改状态
    this.setState({
      todos: newTodos,
    });
  };
  handleDelTodo = (index) => {
    // 深拷贝旧的todos
    let newTodos = JSON.parse(JSON.stringify(this.state.todos));
    newTodos.splice(index, 1);
    // 更改状态
    this.setState({
      todos: newTodos,
    });
  };
  render() {
    return (
      <div>
        <div>
          <input
            type="text"
            value={this.state.inputVal}
            onChange={this.handleChange}
          />
          <button onClick={this.handleAddTodos}>添加</button>
        </div>
        <ul>
          {this.state.todos.map((v, i) => (
            <li key={v.id}>
              {v.text}
              <button onClick={this.handleDelTodo}>删除</button>
            </li>
          ))}
        </ul>
      </div>
    );
  }
}
